package com.icatw.club.service.impl;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icatw.club.domain.ClubCollege;
import com.icatw.club.domain.ClubMember;
import com.icatw.club.domain.ClubPosition;
import com.icatw.club.mapper.ClubMemberMapper;
import com.icatw.club.service.IClubCollegeService;
import com.icatw.club.service.IClubMemberService;
import com.icatw.club.service.IClubPositionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 社团会员Service业务层处理
 *
 * @author icatw
 * @date 2022-06-09
 */
@Service
@Slf4j
public class ClubMemberServiceImpl extends ServiceImpl<ClubMemberMapper, ClubMember> implements IClubMemberService {
    @Autowired
    IClubCollegeService clubCollegeService;
    @Autowired
    IClubPositionService clubPositionService;

    @Override
    public List<ClubMember> selectMemberList(ClubMember clubMember) {
        QueryWrapper<ClubMember> wrapper = new QueryWrapper<>();
        //姓名、专业班级模糊匹配
        //性别，学院==
        if (clubMember != null) {
            if (StrUtil.isNotBlank(clubMember.getMemberName())) {
                wrapper.like("member_name", clubMember.getMemberName());
            }
            if (clubMember.getCollegeId() != null) {
                wrapper.eq("college_id", clubMember.getCollegeId());
            }
            if (StrUtil.isNotBlank(clubMember.getMemberClass())) {
                wrapper.like("member_class", clubMember.getMemberClass());
            }
            if (StrUtil.isNotBlank(clubMember.getMemberSex())) {
                wrapper.like("member_sex", clubMember.getMemberSex());
            }
        }
        List<ClubMember> clubMembers = list(wrapper);
        return getClubMembersWithCollege(clubMembers);
    }

    @Override
    public List<ClubMember> selectMemberList() {
        List<ClubMember> clubMembers = list();
        return getClubMembersWithCollege(clubMembers);
    }

    @Override
    public void export(ModelMap map, HttpServletRequest request, HttpServletResponse response) {
        List<ClubMember> memberList = this.selectMemberList();
        ExportParams params = new ExportParams("会员列表", "会员列表", ExcelType.XSSF);
        map.put(NormalExcelConstants.DATA_LIST, memberList);
        map.put(NormalExcelConstants.CLASS, ClubMember.class);
        map.put(NormalExcelConstants.PARAMS, params);
        map.put(NormalExcelConstants.FILE_NAME, "memberList");
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(MultipartFile file) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        try {
            List<ClubMember> list = ExcelImportUtil.importExcel(
                    file.getInputStream(),
                    ClubMember.class, params);
            //清空id，防止id重复
            List<ClubMember> collect = list.stream().map(m -> {
                log.info(m.toString());
                m.setId(null);
                //因为Excel没有学院id只是传了学院名，因此需要手动查询并查询学院id
                String collegeName = m.getClubCollege().getCollegeName();
                ClubCollege college = clubCollegeService.getOne(new QueryWrapper<ClubCollege>().eq("college_name", collegeName));
                Long cId = college.getCId();
                m.setCollegeId(cId);
                //手动添加职位
                String positionName = m.getClubPosition().getPositionName();
                ClubPosition position = clubPositionService.getOne(new QueryWrapper<ClubPosition>().eq("position_name", positionName));
                Integer pId = position.getPId();
                m.setPositionId(pId);
                //导入信息时设置加入时间为当前时间
                m.setCreateDate(LocalDate.now());
                return m;
            }).collect(Collectors.toList());
            this.saveOrUpdateBatch(collect);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 查询会员信息及其二级学院和职位
     *
     * @param clubMembers 俱乐部成员
     * @return {@link List}<{@link ClubMember}>
     */
    private List<ClubMember> getClubMembersWithCollege(List<ClubMember> clubMembers) {
        List<ClubMember> collect = clubMembers.stream().map(member -> {
            Long collegeId = member.getCollegeId();
            Integer positionId = member.getPositionId();
            ClubCollege college = clubCollegeService.getById(collegeId);
            ClubPosition position = clubPositionService.getById(positionId);
            member.setClubCollege(college);
            member.setClubPosition(position);
            return member;
        }).collect(Collectors.toList());
        log.info(collect.toString());
        return collect;
    }
}
